/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.spring.common.configuration;

import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import java.util.HashSet;
import java.util.Set;
import org.elsfs.cloud.api.security.key.KeyPairRepositoryJWKSource;
import org.elsfs.cloud.api.security.key.OAuth2JWKRepository;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;

/**
 * 密钥对配置
 *
 * @author zeng
 */
@AutoConfiguration
@ConditionalOnBean({OAuth2JWKRepository.class})
public class KeyPairConfiguration {
  @Bean
  PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
  }

  @Bean
  public KeyPairRepositoryJWKSource keyPairRepositoryJWKSource(
      OAuth2JWKRepository keyPairRepository) {
    return new KeyPairRepositoryJWKSource(keyPairRepository);
  }

  @Bean
  NimbusJwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
    // 数字签名 算法
    Set<JWSAlgorithm> jsAlgorithms = new HashSet<>(JWSAlgorithm.Family.SIGNATURE);
    // jwt 处理器
    ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
    JWSKeySelector<SecurityContext> jwsKeySelector =
        new JWSVerificationKeySelector<>(jsAlgorithms, jwkSource);
    // 设置JWS key 选择器。如果没有JWS对象将被拒绝。
    jwtProcessor.setJWSKeySelector(jwsKeySelector);
    // 替换默认的Nimbus声明集验证器，因为NimbusJwtDecoder会处理它
    jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {});
    return new NimbusJwtDecoder(jwtProcessor);
  }

  @Bean
  NimbusJwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
    return new NimbusJwtEncoder(jwkSource);
  }
}
